#include "result.h"
#include "ui_result.h"
#include "history.h"
#include "setting.h"
#include "detection.h"
#include"uploadimage.h"
#include"login.h"
#include<QtDebug>
#include<QFile>
#include<QPdfWriter>
#include<QPainter>
#include<QRect>
#include<QTextOption>

#include<QFileDialog>
#include<QString>
#include"waiting.h"
#include<QFuture>
#include<QtConcurrent>


result::result(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::result)
{
    //设置无边框
    this->setWindowFlags(Qt::FramelessWindowHint);

    ui->setupUi(this);
    ui->label_image->setFrameShape (QFrame::Box);
    ui->label_image->setStyleSheet("border-width: 1px;border-style: solid;border-color: rgb(255, 170, 0);");
    ui->label_result_txt->setFrameShape (QFrame::Box);
    //    ui->label_real_username->setText(QStringLiteral("张三"));//右上角的名字
    //设置窗口图标
//    this->setWindowIcon(QIcon(":/images/软件图标.png"));

    up=new uploadImage;

    this->userName=login::Qname;

    query.exec("select user_id from user where user_name='"+userName+"'");
    query.next();
    this->user_id=query.value(0).toInt();
    qDebug()<<"result: user_id->"<<user_id;

}

result::~result()
{
    delete ui;
    delete up;
}

//保存图片到ct表
void result::savePicture(QString image)
{
    //判断图片在不在数据库

    //    QSqlQuery query;

    QString sql_have_pic="select ct_id from ct where picture='"+image+"'";
    query.exec(sql_have_pic);
    if(query.size()!=0){
        query.next();
        this->ct_id= query.value(0).toInt();
    }
    else{
        int Diagnosis_number=1428390267;//就诊号
        QString sql_insert=QString("insert into %1 (Diagnosis_number,picture) values('%2','%3')").arg("ct").arg(Diagnosis_number).arg(image);
        query.exec(sql_insert);
        //获取插入后的自增id
        QString sql_max_ct_id="select max(ct_id) from ct where picture='"+image+"'";
        query.exec(sql_max_ct_id);
        query.next();
        int id = query.value(0).toInt();
        qDebug()<<"result:ct_id->"<<id;
        this->ct_id=id;
    }




}

//保存检测记录
void result::saveMessage(int id, QString message)
{
    //    QSqlQuery query;
    QString sql_insert_record=QString("insert into %1 (user_id,ct_id,detecting_result) values('%2','%3','%4')").arg("record").arg(user_id).arg(id).arg(message);
    query.exec(sql_insert_record);
    qDebug()<<"result: sql_insert_record->"<<sql_insert_record;

}



//按钮，保存结果
void result::on_pushButton_save_clicked()
{
    //怎么保证图片只上传一次
    if(isPost==false){
        //        up->creat(this->outputImageName);
        Waiting pWait(this);
        pWait.show();
        QFuture<void> fut=QtConcurrent::run([=]()->void{ return
                    up->creat(this->outputImageName);}); //异步处理        while(!future.isFinished())
        while(!fut.isFinished())
        {
            QApplication::processEvents(QEventLoop::AllEvents, 100);//唤醒主界面
        }
        pWait.close();
        isPost=true;
    }
    resultImageUrl=up->getResultImageUrl();

    //保证一个result界面,只保存一次图片
    this->savePicture(this->resultImageUrl);

    //    QString message=QStringLiteral("一共检测到")+QString::number(detectNum)+QStringLiteral("个息肉");
    this->saveMessage(ct_id,message);
    QMessageBox::information(this, QStringLiteral("保存成功"), QStringLiteral("保存结果到数据库成功！"));

}

//按钮：创建pdf
void result::on_pushButton_print_clicked()
{
    qDebug()<<"result: result after upload network addr:"<<up->getResultImageUrl();
    this->createPdfResult(this->outputImageName,"123");
}


//接收图片
void result::getOutputImageName(QString outputImageName,QString mes,bool isN)
{
    this->isNew=isN;
    this->outputImageName=outputImageName;
    //    this->detectNum=num;
    this->message=mes;

    ui->label_result_txt->setText("what happened");
    qDebug()<<"result: userName->"<<this->userName;
    qDebug()<<"result:  new->"<<this->isNew;
    //将图片显示在lable
    qDebug()<<"result: picture addr->"+this->outputImageName;
    //如果有图片地址，则显示出来
    //this->outputImageName="C:\\Users\\lxc18\\Documents\\qt_workspace\\colon_polyp_detection\\build-detecting-Desktop_Qt_5_9_9_MSVC2017_64bit-Debug\\images\\1.jpg";



    QImage* img=new QImage;
    //    QPixmap pic;
    QString filePath = QCoreApplication::applicationDirPath();
    qDebug()<<"result: exe addr->"+filePath;
    qDebug()<<"result: image addr->"+this->outputImageName;

    if(!(img->load(this->outputImageName))) //加载图像(相对路径)
    {
        QFile file(outputImageName);
        if(!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::warning(this,QStringLiteral("图片打开失败"),QStringLiteral("打开图片文件失败！%1").arg(outputImageName));
        }
        else {
            img->loadFromData(file.readAll());
            img->scaled(ui->label_image->size(),Qt::KeepAspectRatio);
            ui->label_image->setScaledContents(true);
            ui->label_image->setPixmap(QPixmap::fromImage((*img)));
        }

    }
    else {
        qDebug()<<"result: img ->"<<img->isNull();
        img->scaled(ui->label_image->size(),Qt::KeepAspectRatio);
        ui->label_image->setScaledContents(true);
        ui->label_image->setPixmap(QPixmap::fromImage((*img)));


    }
    //个数信息
    //        QString message=QStringLiteral("检测到")+QString::number(detectNum)+QStringLiteral("个结直肠息肉");

    ui->label_result_txt->setText(message);
    delete img;

    //判断是否隐藏按钮
    if(isNew==false){
        ui->pushButton_save->hide();
    }
    else{
        ui->pushButton_save->show();
    }
}
//生成pdf文件结果
void result::createPdfResult(QString fileName,QString textResult)
{
    //一、选择保存pdf文件路径
    QString sPath = QFileDialog::getSaveFileName(this, tr("save other"), "/", tr("Text Files (*.pdf)"));
    if(sPath.isEmpty())
    {
        return;
    }
    //    qDebug() << sPath;

    //二、创建pdf文件
    QFile pdfFile(sPath);
    pdfFile.open(QIODevice::WriteOnly);

    //三、创建生成pdf类，作为绘图设备
    QPdfWriter *pPdfWriter = new QPdfWriter(&pdfFile);
    pPdfWriter->setResolution(300);
    pPdfWriter->setPageSize(QPagedPaintDevice::A4);
    pPdfWriter->setPageMargins(QMarginsF(30, 30, 30, 30));

    //四、开始绘制PDF
    //病人信息
    QString realName,realSex,realAge,realID;
    paintPdf(pPdfWriter,QStringLiteral("张三"),QStringLiteral("男"),QStringLiteral("50"),QStringLiteral("1008965"));

//    paintPdf(pPdfWriter,realName,realSex,realAge,realID);

    delete pPdfWriter;
    pdfFile.close();


    qDebug()<<"test  pdf!!!";
}
//绘制pdf
void result::paintPdf(QPagedPaintDevice *device,QString realName,QString realSex,QString realAge,QString realID)
{
    QPainter *pPainter = new QPainter(device);
    //        qDebug() << pPainter->viewport();
    int nPdfWidth = pPainter->viewport().width();
    int nPdfHeight = pPainter->viewport().height();

    //绘制标题
    int y = 10;
    pPainter->setFont(QFont("宋体", 18, 36));
    pPainter->drawText(QRect(0, y, nPdfWidth, 100), Qt::AlignCenter, QStringLiteral("人民医院结直肠息肉检测报告"));

    //病人相关信息
    y+=150;
    pPainter->setFont(QFont("宋体", 14, 36));

    int nUnitW = nPdfWidth / (4+4+4+3+4+3+4+4+8+10);

    int nNameWidth = nUnitW * 4;

    int realNameX=nNameWidth;
    int realNameWidth=nUnitW * 4;

    int nSexX = realNameX+realNameWidth;
    int nSexWidth = nUnitW * 4;

    int realSexX=nSexX + nSexWidth;
    int realSexWidth=nUnitW * 3;

    int nAgeX = realSexX + realSexWidth;
    int nAgeWidth = nUnitW * 4;


    int realAgeX = nAgeX + nAgeWidth;
    int realAgeWidth = nUnitW * 3;


    int nOfficeX = realAgeX + realAgeWidth;
    int nOffiWidth = nUnitW * 4;

    int realOfficeX = nOfficeX + nOffiWidth;
    int realOffiWidth = nUnitW * 4;

    int nIDX = realOfficeX + realOffiWidth;
    int nIDWidth = nUnitW * 8;

    int realIDX = nIDX + nIDWidth;
    int realIDWidth = nUnitW * 6;

    int nLineHeight = 120;

    //中文乱码+传参
    pPainter->drawText(QRect(0, y, nNameWidth, nLineHeight), Qt::AlignHCenter, QStringLiteral("姓名："));
//    QString realName="张三";
    qDebug()<<realName;
    QByteArray bytes = realName.toUtf8();// QString转QByteArray方法1
//    QString test=QString::fromUtf8(realName);
    QString reals=bytes;
    qDebug()<<bytes;
    qDebug()<<reals;
    pPainter->drawText(QRect(realNameX, y, realNameWidth, nLineHeight), Qt::AlignHCenter, reals);

    pPainter->drawText(QRect(nSexX, y, nSexWidth, nLineHeight), Qt::AlignHCenter, QStringLiteral("性别："));
//    QString realSex="男";
    pPainter->drawText(QRect(realSexX, y, realSexWidth, nLineHeight), Qt::AlignHCenter, realSex);


    pPainter->drawText(QRect(nAgeX, y, nAgeWidth, nLineHeight), Qt::AlignHCenter, QStringLiteral("年龄："));
//    QString realAge="50";
    pPainter->drawText(QRect(realAgeX, y, realAgeWidth, nLineHeight), Qt::AlignHCenter, realAge);


    pPainter->drawText(QRect(nOfficeX, y, nOffiWidth, nLineHeight), Qt::AlignHCenter, QStringLiteral("科室："));
    QString realOffice=QStringLiteral("内科");
    pPainter->drawText(QRect(realOfficeX, y, realOffiWidth, nLineHeight), Qt::AlignHCenter, realOffice);

    pPainter->drawText(QRect(nIDX, y, nIDWidth, nLineHeight), Qt::AlignHCenter, QStringLiteral("就诊号："));
//    QString realID="10086";
    pPainter->drawText(QRect(realIDX, y, realIDWidth, nLineHeight), Qt::AlignHCenter, realID);

    //绘制一条分隔线
    y += 100;
    pPainter->setPen(QPen(QBrush(QColor(144, 166,188)), 8));
    pPainter->drawLine(QLineF(0, y, nPdfWidth, y));
    //影像标本：
    y+=100;
    pPainter->setPen(QPen(QBrush(QColor(0, 0,0)), 8));
    pPainter->drawText(QRect(0, y, nPdfWidth, nLineHeight), Qt::AlignLeft, QStringLiteral("影像标本:"));
    //画图
    //         int temp=y;//记录一下y的高度
    QString pixPath=this->outputImageName;

    QPixmap pixmap(pixPath);
    pixmap=pixmap.scaled(1500,1500,Qt::KeepAspectRatio,Qt::SmoothTransformation);

    //         QRect rect = pPainter->viewport();
    //        int multiple = rect.width()/pixmap.width()/2;
    //        pPainter->scale(multiple, multiple); //将图像(所有要画的东西)在pdf上放大multiple-1倍
    y+=100;
    pPainter->drawPixmap(30,y,pixmap);


    //影像结果：
    y=y+1600;
    pPainter->setPen(QPen(QBrush(QColor(0, 0,0)), 8));
    pPainter->drawText(QRect(0, y, nPdfWidth, nLineHeight), Qt::AlignLeft, QStringLiteral("影像结果:"));
    y+=100;
    QString resultMessage=this->message;
    pPainter->drawText(QRect(0, y, nPdfWidth, nLineHeight), Qt::AlignLeft, resultMessage);



    //分割线
    //绘制一条分隔线
    y =nPdfHeight-500;
    pPainter->setPen(QPen(QBrush(QColor(144, 166,188)), 8));
    pPainter->drawLine(QLineF(0, y, nPdfWidth, y));

    //备注：
    y+=100;
    pPainter->setPen(QPen(QBrush(QColor(0, 0,0)), 8));
    int temp=nPdfWidth/10;
    int l=temp*7;
    pPainter->drawText(QRect(0, y, l, nLineHeight), Qt::AlignLeft, QStringLiteral("备注："));
    pPainter->drawText(QRect(l, y, nPdfWidth-l, nLineHeight), Qt::AlignLeft, QStringLiteral("  医生："));
    //医生签字
    y+=60;
    pPainter->drawText(QRect(l, y, nPdfWidth-l, nLineHeight), Qt::AlignLeft, QStringLiteral("（签字有效）"));

    //日期

    y+=300;
//    QString checkTime=QDateTime::currentDateTime().toString(Qt::ISODate);//从数据库中获得
//    pPainter->drawText(QRect(0, y,temp*1.5, nLineHeight), Qt::AlignLeft, QStringLiteral("检验时间："));
//    pPainter->drawText(QRect(temp*1.5, y,nPdfWidth, nLineHeight), Qt::AlignLeft, checkTime);
    y+=100;
    QString currentTime=QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");//获取当前时间
    pPainter->drawText(QRect(0, y, temp*1.5, nLineHeight), Qt::AlignLeft, QStringLiteral("报告时间："));
    pPainter->drawText(QRect(temp*1.5, y, nPdfWidth, nLineHeight), Qt::AlignLeft, currentTime);



    delete pPainter;
}

//字符串获取息肉个数
void result::getNumber(QString msg)
{
    int  n;
    QRegExp rx("(\\d+)");  // 匹配数字
    int pos = 0;
    while ((pos = rx.indexIn(msg, pos)) != -1) {
        n= rx.cap(0).toInt();
        pos += rx.matchedLength();
    }
    this->detectNum=n;
//    return nTime;
    //qDebug( )<<nTime;

}
//息肉个数转为message
void result::setMessage(int num)
{
    this->message=QStringLiteral("检测到")+QString::number(num)+QStringLiteral("个结直肠息肉");
}


//检测结果，修改检测数据（例如检测个数）
void result::on_pushButton_2_clicked()
{
    this->getNumber(this->message);
    qDebug()<<"msgh:"<<this->message;
    ui->lineEdit->setText(QString::number(this->detectNum));
    ui->stackedWidget->setCurrentIndex(1);
}




//修改后，跳转到原来的展示界面
void result::on_pushButton_clicked()
{
    this->detectNum = ui->lineEdit->text().toInt();
    this->setMessage(this->detectNum);
    ui->label_result_txt->setText(this->message);
    ui->stackedWidget->setCurrentIndex(0);
}

//不修改，直接返回
void result::on_pushButton_3_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

